<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let list = [
        { id: 1, name: "部门A", parentId: 2 },
        { id: 2, name: "部门B", parentId: 5 },
        { id: 3, name: "部门C", parentId: 4 },
        { id: 4, name: "部门D", parentId: 0 },
        { id: 5, name: "部门E", parentId: 0 },
        { id: 6, name: "部门F", parentId: 13 },
        { id: 7, name: "部门G", parentId: 10 },
        { id: 8, name: "部门H", parentId: 7 },
        { id: 9, name: "部门H", parentId: 7 },
        { id: 10, name: "部门H", parentId: 2 },
        { id: 11, name: "部门H", parentId: 2 },
        { id: 12, name: "部门H", parentId: 6 },
      ];
      let newArr = [];
      // 先找到parentId为0的 放到新数组中
      // 遍历剩下的数组 根据剩下数组的parentId去递归查找parentId为0的项是否有其父级有插入 没有插入父数组中
      function convert(list) {
        let res = [];
        let map = new Map();
        for (let i = 0; i < list.length; i++) {
          map.set(list[i].id, list[i]);
        }
        for (let i = 0; i < list.length; i++) {
          let pid = list[i].parentId;
          if (map.has(pid)) {
            let val = map.get(pid);
            val.children
              ? val.children.push(list[i])
              : (val.children = [list[i]]);
          } else {
            res.push(list[i]);
          }
        }
        console.log(res);
      }

      convert(list);
    </script>
  </body>
</html>
